package fun.tan90.easy.binlog.plugin.mysql.config;

import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.model.OutputParam;
import fun.tan90.easy.binlog.plugin.mysql.model.MysqlClientParams;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.noear.dami.Dami;

import java.util.Objects;

/**
 * description 动态连接mqtt
 * company 铁人科技
 *
 * @author Li YuLong
 * @date 2023/8/17 10:56
 */
@Slf4j
public class MysqlClientCacheLoader implements CacheLoader<String, HikariDataSource> {

    @Override
    public @Nullable HikariDataSource load(@NonNull String outputCode) throws Exception {
        OutputParam outputParam = Dami.<String, OutputParam>bus().sendAndRequest(DamiEventConstants.OUTPUT_PARAM_TOPIC, outputCode);
        if (Objects.isNull(outputParam)) {
            return null;
        }

        MysqlClientParams mysqlClientParams = (MysqlClientParams) outputParam;

        HikariConfig config = new HikariConfig();
        config.setPoolName("easy-binlog-" + outputCode);
        config.setJdbcUrl(StrUtil.format("jdbc:mysql://{}/{}", mysqlClientParams.getJdbcUrl(), mysqlClientParams.getDatabaseName()));
        config.setUsername(mysqlClientParams.getUsername());
        config.setPassword(mysqlClientParams.getPassword());

        config.setMaximumPoolSize(mysqlClientParams.getMaxPoolSize());
        config.setMinimumIdle(mysqlClientParams.getMinIdle());

        return new HikariDataSource(config);
    }
}
